package com.ttmusic.fragments.maintab;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.ttmusic.activitys.MainActivity;
import com.ttmusic.activitys.R;
import com.ttmusic.core.MusicManager;
import com.ttmusic.entity.LrcContent;
import com.ttmusic.utils.ILrcStateContain;
import com.ttmusic.utils.LrcUtil;
import com.ttmusic.utils.OnlineLrcUtil;
import com.ttmusic.utils.TimeUtil;
import com.ttmusic.utils.Utils;
import com.ttmusic.view.LrcView;
import com.ttmusic.view.listeners.OnLrcSearchClickListener;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class LyricFragment extends Fragment implements OnClickListener, OnLrcSearchClickListener, OnSeekBarChangeListener, ILrcStateContain {
	
	private View view;
	//顶部的歌曲名称和艺术家名称
	private TextView lyricActionBar_title, lyricActionBar_artist;
	//顶部返回主界面 、展示右侧侧滑菜单
	private ImageView icon_back_tomain, icon_show_asidemenu;
	//底部进度条
	private SeekBar playpage_progressbar;
	//底部已播放时间 和 总时长
	private TextView playpage_playtime_tv, playpage_duration_tv;
	//底部上一首 和 下一首
	private ImageView playpage_previous, playpage_next;
	//底部播放暂停按钮
	private ToggleButton playpage_play_pause;
	//提供给MusicManager改变界面显示状态
	private Handler lyricHandler;
	//已播放时长字符串的处理  每一秒改变一次
	private Handler playedTimeHandler;
	//SeekBar进度改变处理
	private Handler seekBarHandler;
	//任务调度器 每一秒改变一次已播放时间字符串  每50毫秒改变一次SeekBar进度条的进度
	private Timer timer;
	
	//歌词栏
	private LrcView playpage_lrcview;
	private DrawerLayout dl_music_queue;
	//下载歌词文件的远程url
	private String lrcDownloadUrl;
	//歌词文件名称
	private String lrcName = "";
	//歌词栏右侧的侧滑菜单
	private ListView lv_music_queue;
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_lyric, container, false);
		return view;
	}

	@SuppressLint("HandlerLeak")
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		timer = new Timer();
		//顶部组件初始化
		icon_back_tomain = (ImageView)view.findViewById(R.id.icon_back_tomain);
		icon_back_tomain.setOnClickListener(this);
		lyricActionBar_title = (TextView)view.findViewById(R.id.lyricActionBar_title);
		lyricActionBar_title.setOnClickListener(this);
		lyricActionBar_artist = (TextView)view.findViewById(R.id.lyricActionBar_artist);
		lyricActionBar_artist.setOnClickListener(this);
		icon_show_asidemenu = (ImageView)view.findViewById(R.id.icon_show_asidemenu);
		icon_show_asidemenu.setOnClickListener(this);
		
		//底部组件初始化
		playpage_progressbar = (SeekBar)view.findViewById(R.id.playpage_progressbar);
		playpage_progressbar.setOnSeekBarChangeListener(this);
		//已播放时间字符串
		playpage_playtime_tv = (TextView)view.findViewById(R.id.playpage_playtime_tv);
		//总时长字符串
		playpage_duration_tv = (TextView)view.findViewById(R.id.playpage_duration_tv);
		//播放控制按钮
		playpage_previous = (ImageView)view.findViewById(R.id.playpage_previous);
		playpage_previous.setOnClickListener(this);
		playpage_next = (ImageView)view.findViewById(R.id.playpage_next);
		playpage_next.setOnClickListener(this);
		playpage_play_pause = (ToggleButton)view.findViewById(R.id.playpage_play_pause);
		playpage_play_pause.setOnClickListener(this);
		if(!MainActivity.mManager.isPlaying()) {
			playpage_play_pause.setChecked(false);
		}
		
		
		//初始化handler MusicManager每次播放完毕一首歌自动切换下一首时 触发
  		lyricHandler = new Handler() {
  			@Override
  			public void handleMessage(Message msg) {
  				//加载歌词
  				loadLrcView();
  				updateTopAndBottomActionBar();
  			}
  		};
  		//很重要***********   传递给MusicManager 用来回传消息
  		MainActivity.mManager.setHandler(lyricHandler);
  		
  		//已播放时长字符串的处理  每一秒改变一次
  		playedTimeHandler = new Handler() {
  			@Override
  			public void handleMessage(Message msg) {
  				int played = MainActivity.mManager.getCurrentProgress();
  				if(played <= MusicManager.getNowPlayingSong().getDuration()) {
  					playpage_playtime_tv.setText(TimeUtil.mill2mmss(played));
  					updateLrcView(played);
  				}
  			}
  		};
  		
  		//SeekBar进度  每50毫秒改变一次
  		seekBarHandler = new Handler() {
  			@Override
  			public void handleMessage(Message msg) {
  				int played = MainActivity.mManager.getCurrentProgress();
  				if(played <= MusicManager.getNowPlayingSong().getDuration()) {
	  				playpage_progressbar.setProgress(played);
  				}
  			}
  		};
		
		//歌词栏
  		dl_music_queue = (DrawerLayout)view.findViewById(R.id.dl_music_queue);
		playpage_lrcview = (LrcView)view.findViewById(R.id.playpage_lrcview);
		playpage_lrcview.setOnLrcSearchClickListener(this);
		this.loadLrcView();
		lv_music_queue = (ListView)view.findViewById(R.id.lv_music_queue);
		lv_music_queue.setAdapter(MainActivity.adapterCurrentPlay);
		
		//第一次进入歌词Fragment展示   开启定时器并隐藏顶部和底部actionBar
		this.onHiddenChanged(false);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.lyricActionBar_title:
			case R.id.lyricActionBar_artist:
			case R.id.icon_back_tomain:		//返回主界面
				timer.purge();
				if (isDrawerOpen()) {
		            closeDrawer();
		        }
				Utils.go(this.getActivity().getSupportFragmentManager(), this, MainActivity.previous, R.id.framecontent);
				break;
			case R.id.icon_show_asidemenu:
				this.btn_show_music_queueWasClicked();
				break;
			case R.id.playpage_previous:	//上一首
				MainActivity.mManager.preSong();
				break;
			case R.id.playpage_next:		//下一首
				MainActivity.mManager.nextSong(true);
				break;
			case R.id.playpage_play_pause:	//播放、暂停
				if(!playpage_play_pause.isChecked()) {
					//播放中   就暂停并记录播放进度 更改图标为播放按钮 由于本身是ToggleButton 所以不需要用代码来更改图标了
					MainActivity.mManager.pause();
				}else {
					//暂停中   就恢复播放 更改图标为暂停按钮
					MainActivity.mManager.playAfterPause();
				}
				break;
			default:
				break;
		}
	}

	/**
	 * 本fragment显示和隐藏监听
	 */
	@Override
	public void onHiddenChanged(boolean ishidden) {
		MainActivity main = (MainActivity)this.getActivity();
		if(!ishidden) {
//			Toast.makeText(getContext(), "歌词界面显示了", Toast.LENGTH_LONG).show();
			MainActivity.mManager.setHandler(lyricHandler);
			this.updateTopAndBottomActionBar();
			this.autoChangePlayedTimeStr();
			this.autoChangeSeekBarProgress();
			this.loadLrcView();
			
			lv_music_queue.setAdapter(MainActivity.adapterCurrentPlay);
			lv_music_queue.smoothScrollToPosition(MusicManager.getNowPlayingIndex());
			//歌词Fragment展示   就隐藏顶部和底部actionBar
			main.setTopAndBottomActionBarVisibility(View.GONE, View.GONE);
		} else {
//			Toast.makeText(getContext(), "歌词界面隐藏了", Toast.LENGTH_LONG).show();
			//歌词Fragment隐藏    就展示顶部和底部actionBar
			main.setTopAndBottomActionBarVisibility(View.VISIBLE, View.VISIBLE);
			timer.purge();
		}
		super.onHiddenChanged(ishidden);
	}
	
	/**
	 * 更新顶部和底部ActionBar的播放状态和文字
	 */
	private void updateTopAndBottomActionBar() {
		lyricActionBar_title.setText(MusicManager.getNowPlayingSong().getTitle());
		lyricActionBar_artist.setText(MusicManager.getNowPlayingSong().getArtist());
		playpage_progressbar.setMax(MusicManager.getNowPlayingSong().getDuration());
		playpage_duration_tv.setText(MusicManager.getNowPlayingSong().getDurationStr());
		lyricActionBar_title.requestFocus();//得到焦点
		if(!MainActivity.mManager.isPlaying()) {
			playpage_play_pause.setChecked(false);
		}
		//右侧侧滑菜单在展示状态
		if (isDrawerOpen()) {
			MainActivity.adapterCurrentPlay.notifyDataSetChanged();
    		lv_music_queue.smoothScrollToPosition(MusicManager.getNowPlayingIndex());
		}
	}
	
	/**
	 * 每一秒自动改变一次歌词界面 已播放时间字符串  playpage_playtime_tv
	 */
	private void autoChangePlayedTimeStr() {
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				if(MusicManager.isAllowProgressBarChanging)
					playedTimeHandler.sendMessage(new Message());
			}
		}, 0, 1000);
	}
	
	/**
	 * 每50毫秒自动改变一次SeekBar进度
	 */
	private void autoChangeSeekBarProgress() {
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				if(MusicManager.isAllowProgressBarChanging)
					seekBarHandler.sendMessage(new Message());
			}
		}, 0, 50);
	}
	
	//-----------------------------------歌词滚动-------------------------------------
	/**
	 * 随着进度条的进度改变 同步滚动歌词
	 * @param currentTime
	 */
	private void updateLrcView(int currentTime) {
        int tempIndex = playpage_lrcview.getIndexByLrcTime(currentTime);
        if (tempIndex != playpage_lrcview.getIndex()) {
            playpage_lrcview.setIndex(tempIndex);
            playpage_lrcview.invalidate();
        }
    }
	
	/**
	 * 展示和隐藏右侧侧滑菜单
	 */
	private void btn_show_music_queueWasClicked() {
        if (isDrawerOpen()) {
            closeDrawer();
            icon_show_asidemenu.setImageResource(R.drawable.icon_show_asidemenu);
        } else {
        	openDrawer();
        	icon_show_asidemenu.setImageResource(R.drawable.icon_show_asidemenu_press);
        	lv_music_queue.setAdapter(MainActivity.adapterCurrentPlay);
    		lv_music_queue.smoothScrollToPosition(MusicManager.getNowPlayingIndex());
        }
    }

	/**
	 * 开始绘制歌词
	 */
    public void openDrawer() {
        dl_music_queue.openDrawer(Gravity.END);
    }

    /**
     * 关闭绘制
     */
    public void closeDrawer() {
        dl_music_queue.closeDrawers();
    }

    /**
     * 是否已开启
     * @return
     */
    public boolean isDrawerOpen() {
    	if(null != dl_music_queue)
    		return dl_music_queue.isDrawerOpen(Gravity.END);
    	return false;
    }

    /**
     * 加载歌词
     */
	private void loadLrcView() {
        List<LrcContent> lrcLists = null;
        //读取本地歌词  若本地没有再联网加载
        lrcLists = LrcUtil.loadLocalLrc(this.getContext());
        playpage_lrcview.setLrcLists(lrcLists);
        playpage_lrcview.setLrcState(lrcLists.size() == 0 ? READ_LOC_FAIL : READ_LOC_OK);
//        if(lrcLists.size() > 0) {
//        	playpage_lrcview.setIndex(0);//绘制完毕后展示歌词的开头部分
//        }
    }

	/**
	 * 当屏幕出现“暂无歌词,点击开始联网搜索”时，点击开始联网搜索下载
	 * @param view
	 */
	@SuppressLint("HandlerLeak")
	@Override
	public void onLrcSearchClicked(View view) {
        String title = MusicManager.getNowPlayingSong().getTitle();		//歌曲名称 不带歌手名称 不带后缀
        String artist = MusicManager.getNowPlayingSong().getArtist();	//歌手名称
        if(title.indexOf("-") >= 0) {
        	String titleTrim = "";
        	String[] ss = title.split("-");
        	//有可能歌曲名称里面包含多个-符号
        	for(int i=0;i<ss.length;i++) {
        		titleTrim += ss[i].trim() + "-";
        	}
        	if(title.endsWith("-")) {
        		titleTrim = titleTrim.substring(0, titleTrim.length()-1);
        	}
        	title = titleTrim.trim();
        }
        //包含括号的不正规名称
    	if(title.contains("(") && title.contains(")")) {
    		title = title.substring(0, title.indexOf("(")).trim();
    	}
        lrcName = artist + "-" + title + ".lrc";
//		System.out.println("搜索 " + lrcName);
        
        //获取下载歌词文件的远程url
        OnlineLrcUtil.getInstance().getLrcURL(title, artist, new Handler() {
        	//状态值请参考 ILrcStateContain接口中第二段联网状态
			@Override
			public void handleMessage(Message msg) {
				playpage_lrcview.setLrcState(msg.what);//修改界面状态
				if (msg.what == QUERY_ONLINE_OK) {
					lrcDownloadUrl = msg.obj.toString();
					downloadLrcFile();
				}
			}
        });
//		File f = new File(LrcUtil.lrcRootPath);
//		System.out.println(f.listFiles().length + " 个歌词文件");
//		for(File fs : f.listFiles()) {
//			System.out.println(fs.getAbsolutePath());
//			fs.delete();
//		}
	}
	
	@SuppressLint("HandlerLeak")
	private void downloadLrcFile() {
		if(null != lrcDownloadUrl && !"".equals(lrcDownloadUrl)) {
        	//地址获取到了，就开始下载到本地  默认保存到 内部存储/Music/Musiclrc/下
        	String lrcPath = LrcUtil.lrcRootPath + lrcName;
        	System.out.println(lrcPath);
        	OnlineLrcUtil.getInstance().wrtieLrcContentFromUrlToLocal(lrcDownloadUrl, lrcPath, new Handler() {
				@Override
				public void handleMessage(Message msg) {
					playpage_lrcview.setLrcState(msg.what);
					if(msg.what == DOWNLOAD_ONLINE_OK) {
						//下载成功 就再从本地加载
			        	loadLrcView();
					}
				}
        	});
        }
	}
	


	//----------------------------SeekBar进度触摸拖动事件-------------------------------------
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean isuser) {
		
	}
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		MusicManager.isAllowProgressBarChanging = false;
	}
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		MusicManager.isAllowProgressBarChanging = true;
		MainActivity.mManager.seekTo(seekBar.getProgress());
	}
	//----------------------------SeekBar进度触摸拖动事件-------------------------------------
}
